//
//  ZRLoginController.m
//  SinaByOC
//
//  Created by 张锐 on 16/3/16.
//  Copyright © 2016年 zhangr. All rights reserved.
//
/*
 APP_KEY 3354128731
 APP_SECRET 135a713c4107ce894c8d8bfc27d06b9d
 BACK_URL https://www.baidu.com
 
 
 */
#import "NetTool.h"
#import "ZRLoginController.h"
#import "ZRAccessTokenModel.h"
#import "ZRUserInfoModel.h"
#import "ZRWelcomeController.h"

static NSString * APP_KEY = @"3354128731";

static NSString * APP_SCRECT = @"135a713c4107ce894c8d8bfc27d06b9d";

static NSString * BACK_URL = @"https://www.baidu.com";

@interface ZRLoginController ()<UIWebViewDelegate>

@property (nonatomic,strong) UIWebView * webView;

@end

@implementation ZRLoginController

-(void)loadView{

    self.webView = [[UIWebView alloc]init];
    
    self.webView.delegate = self;
    
    self.view = self.webView;

}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self loadRequestForWebView];
    
    [self setupNav];
    
}
/**
 *  webView加载登录页面
 */
-(void)loadRequestForWebView{

    
    NSString * URLString = [NSString stringWithFormat:@"https://api.weibo.com/oauth2/authorize?client_id=%@&redirect_uri=%@&response_type=code",APP_KEY,BACK_URL];
    
    NSURL * url = [NSURL URLWithString:URLString];
    
    NSURLRequest * request = [NSURLRequest requestWithURL:url];
    
    [self.webView loadRequest:request];
    

}
#pragma mark - Nav相关
/**
 *  加入Nav两侧按钮
 */
-(void)setupNav{

    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"返回" style:UIBarButtonItemStylePlain target:self action:@selector(backBarButtonItemClick)];
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"自动填充" style:UIBarButtonItemStylePlain target:self action:@selector(fillUserNameAndPassWord)];


}
/**
 *  返回按钮点击
 */
-(void)backBarButtonItemClick{

    [self dismissViewControllerAnimated:YES completion:^{
        
    }];
}
/**
 *  自动填充按钮
 */
-(void)fillUserNameAndPassWord{
    
    NSString * js = @"document.getElementById(\"userId\").value = \"15114604266\";document.getElementById(\"passwd\").value = \"lashinidie123\"";

    [self.webView stringByEvaluatingJavaScriptFromString:js];
}

#pragma  mark - webView代理
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{
    
    NSString * str = request.URL.absoluteString;
    
    if ([str hasPrefix:BACK_URL]) {
        
        NSString *code = [str componentsSeparatedByString:@"="].lastObject;
        
        [self getAccess_tokenByCode:code];
        
        return NO;
    }

    return YES;
}
/**
 *  通过code获取accesstoken
 *
 *  @param code code
 */
-(void)getAccess_tokenByCode:(NSString *)code{
    
    NSString * urlstring =@"https://api.weibo.com/oauth2/access_token";
    
    /*
     
     必选	类型及范围	说明
     client_id	true	string	申请应用时分配的AppKey。
     client_secret	true	string	申请应用时分配的AppSecret。
     grant_type	true	string	请求的类型，填写authorization_code
     
     grant_type为authorization_code时
     必选	类型及范围	说明
     code	true	string	调用authorize获得的code值。
     redirect_uri	true	string	回调地址，需需与注册应用里的回调地址一致。
     */
    
    NSDictionary * parameters = @{
                                  @"client_id":APP_KEY,
                                  @"client_secret":APP_SCRECT,
                                  @"grant_type":@"authorization_code",
                                  @"code":code,
                                  @"redirect_uri":BACK_URL
                                  };

    [NetTool networkingToolWithType:@"post" andURLString:urlstring andParameters:parameters andSuccessBlock:^(id responseObject) {
        
        NSDictionary * dict = (NSDictionary *)responseObject;
        
        ZRAccessTokenModel * model = [ZRAccessTokenModel accessTokenModelWithDictionary:dict];
        
        NSUserDefaults * ud = [NSUserDefaults standardUserDefaults];
        
        [ud setObject:model.access_token forKey:@"access_token"];
        
        [ud setObject:model.expires_in forKey:@"expires_in"];
        
        [ud setObject:model.uid forKey:@"uid"];
        
        [self getUersInfoByAccessTokenModel:model];
        
    }];


}
/**
 *  通过access_token model 获取用户信息
 *
 *  @param model model
 */
-(void)getUersInfoByAccessTokenModel:(ZRAccessTokenModel *)model{

    NSString * urlString =@"https://api.weibo.com/2/users/show.json";
    
    /*
     
     必选	类型及范围	说明
     access_token	true	string	采用OAuth授权方式为必填参数，OAuth授权后获得。
     uid	false	int64	需要查询的用户ID
     
     */
    NSDictionary * parameters = @{
                                  @"access_token": model.access_token,
                                  @"uid":model.uid
                                  };

    [NetTool networkingToolWithType:@"get" andURLString:urlString andParameters:parameters andSuccessBlock:^(id responseObject) {
       
        NSDictionary * dict = (NSDictionary *)responseObject;
        
        ZRUserInfoModel * model = [ZRUserInfoModel userInfoModelByDictionary:dict];
        
        NSUserDefaults * ud = [NSUserDefaults standardUserDefaults];
        
        [ud setObject:model.screen_name forKey:@"screen_name"];
        
        [ud setObject:model.profile_image_url forKey:@"profile_image_url"];
        
        [self presentViewController: [[ZRWelcomeController alloc]init] animated:YES completion:^{}];
        
    }];
}



@end
